package org.hilo.boot.core.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.subject.support.WebDelegatingSubject;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

/**
 * 用于生成SessionId和验证
 * 
 * @author zollty
 * @since 2018年4月4日
 */
@SuppressWarnings("deprecation")
public class SessionEncoder {
    
    private static PasswordEncoder psEncoder = new StandardPasswordEncoder();
    
    public static String encode(CharSequence rawPassword) {
        return psEncoder.encode(rawPassword);
    }
    
    public static boolean matches(CharSequence rawPassword, String encodedPassword) {
        return psEncoder.matches(rawPassword, encodedPassword);
    }
    
    public static String getUserAgent() {
        Subject subject = SecurityUtils.getSubject();
        if(subject instanceof WebDelegatingSubject) {
            WebDelegatingSubject webSubject = (WebDelegatingSubject) subject;
            ServletRequest request = webSubject.getServletRequest();
            if(request instanceof HttpServletRequest) {
                HttpServletRequest wrequest = (HttpServletRequest) request;
                String userAgent = wrequest.getHeader("User-Agent");
                return userAgent;
            }
        }
        return null;
    }

}
  
